// 图表统计
import type {
  ChartsStasticStateType,
  PieChartDataListItem,
  ChartsStasticDataListDataListItem
} from './typings'
import { defineComponent, reactive, onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import { ElCard, ElDatePicker, ElIcon, ElRow, ElCol, ElImage } from 'element-plus'
import { Remove } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash'
import PieChart from '~/pages/assetOverview/components/PieChart' // 工区总设施投入占比图
import BarChart from '~/pages/assetOverview/components/BarChart' // 工区设施投入对比图
import LineChart from '~/pages/assetOverview/components/LineChart' // 月度设施投入走势图
import BarLampPostChart from '~/pages/assetOverview/components/BarLampPostChart'
import LineStreetChart from '~/pages/assetOverview/components/LineStreetChart'
import ChartsStatisticOption from './ChartsStatisticOption'
import SaasTitle from '~/components/SaasTitle'
// import AliIcon from '~/components/AliIocn'
import plusImg from '~/assets/plus.png'
import styles from '~/pages/assetOverview/index.module.scss'
import { EL_SPACE_SIZE_SECOND_GEAR, SPAN_STYLE_DOUBLE } from '~/utils/const'
import day from 'dayjs'

export default defineComponent(function ChartsStastic() {
  const store = useStore()
  /* 初始值 */
  const state = reactive<ChartsStasticStateType>({
    showChartsStatisticOption: false, // 图表统计 显隐弹窗是否显示
    chartsStasticDataList: [], // 设置遍历的数据
    pieChartDataList: [], // 工区总设施投入占比图 数据源
    barChartDataList: [], // 工区设施投入对比图 数据源
    lineChartDataList: [], // 月度设施投入走势图 数据源
    yearData: [], // 走势图的下拉框筛选 年数据
    lampPostList: {}, //  杆高分类统计
    streetList: []
  })
  const stateCharts = ref<ChartsStasticStateType['chartsStasticDataList']>()
  const userInfo = JSON.parse(localStorage.getItem('saber-userInfo')!) // 获取当前登录人

  onMounted(() => {
    refreshDate()
    getPieChartDataList() // 工区总设施投入占比图 数据源
    getBarChartDataList() // 工区设施投入对比图 数据源
    getLineChartDataList() // 月度设施投入走势图 数据源
    getYearData()
    getLampPostList()
    // getStreetList()
  })

  // 刷新后, 清空上次搜索的日期
  const refreshDate = () => {
    initData()
  }

  // 主内容
  const handleGetChartsStasticData = () => {
    state.chartsStasticDataList = []
    const info = cloneDeep(
      JSON.parse(localStorage.getItem(`assetOverviewCardsInfo${userInfo.content.userId}`)!)
    ) // 所有缓存
    const orderInfo = cloneDeep(
      JSON.parse(localStorage.getItem(`assetOverviewCardsOrder${userInfo.content.userId}`)!)
    ) // 上次缓存数据

    stateCharts.value = [
      {
        type: 'zhanbitu',
        components: (
          <div class={styles['statistic-pieChart']}>
            <div class={styles['statistic-pieCircle']}></div>
            <PieChart dataList={state.pieChartDataList} />
          </div>
        )
      },
      {
        type: 'duibitu',
        components: (
          <div class={styles['statistic-barChart']}>
            <BarChart id="sheshitouru" dataList={state.barChartDataList} />
          </div>
        )
      },
      {
        type: 'zoushitu',
        components: (
          <div class={styles['statistic-barChart']}>
            <LineChart dataList={state.lineChartDataList} />
          </div>
        )
      },
      {
        type: 'tongjitu',
        components: (
          <div class={styles['statistic-barChart']}>
            <LineStreetChart id="jiedaosheshi" dataList={state.streetList} />
          </div>
        )
      },
      {
        type: 'gangaofenlei',
        components: (
          <div class={styles['statistic-barChart']}>
            <BarLampPostChart id="gangaofenlei" dataList={state.lampPostList} />
          </div>
        )
      }
    ]
    if (info) {
      // 非初次缓存 获取原来的值
      state.chartsStasticDataList = orderInfo
    } else {
      initData()
    }
  }

  const initData = () => {
    // 初次缓存 设置遍历的数据
    const timeDay = day().subtract(1, 'year').format('YYYY-MM-DD')

    setTimeout(() => {
      state.chartsStasticDataList = [
        {
          show: true,
          type: 'zhanbitu',
          name: '区域总设施投入占比图',
          backgroundImage: '/assetOverview/accountePie.png',
          deliverDate: [timeDay, day().format('YYYY-MM-DD')]
        },
        {
          show: true,
          type: 'duibitu',
          name: '区域设施投入占比图',
          backgroundImage: '/assetOverview/contrastBar.png',
          deliverDate: [timeDay, day().format('YYYY-MM-DD')]
        },
        {
          show: true,
          type: 'zoushitu',
          name: '月度设施投入走势图',
          backgroundImage: '/assetOverview/movementsLine.png',
          deliverDate: day().format('YYYY')
        },
        {
          show: true,
          type: 'tongjitu',
          name: '街道设施分布统计图',
          backgroundImage: '/assetOverview/jiedaofenbu.png'
          // deliverDate: day().format('YYYY')
        },
        {
          show: true,
          type: 'gangaofenlei',
          name: '杆高分类统计图',
          backgroundImage: '/assetOverview/denggangaodu.png'
          // deliverDate: day().format('YYYY')
        }
      ]

      // 卡片显隐 做本地浏览器缓存 初次缓存时 全部数据和上次顺序是相同值
      window.localStorage.setItem(
        `assetOverviewCardsInfo${userInfo.content.userId}`,
        JSON.stringify(state.chartsStasticDataList)
      )
      window.localStorage.setItem(
        `assetOverviewCardsOrder${userInfo.content.userId}`,
        JSON.stringify(state.chartsStasticDataList)
      )
    }, 100)
  }

  // 工区总设施投入占比图 数据源
  const getPieChartDataList = async (value?: string[]) => {
    let res
    value
      ? (res = await store.dispatch('assetOverview/GetAssetModelAreaRatioReport', {
          deliverDateBegin: value[0],
          deliverDateEnd: value[1]
        }))
      : (res = await store.dispatch('assetOverview/GetAssetModelAreaRatioReport'))

    state.pieChartDataList = []
    if (res?.code === 200) {
      res.data.map((item: PieChartDataListItem) =>
        item.num === 0
          ? ''
          : state.pieChartDataList.push({
              num: item.num,
              areaName: item.areaName
            })
      )
    }
    handleGetChartsStasticData() // 更新视图
  }

  const getLampPostList = async () => {
    const xAxis: any[] = []
    const ydata: any[] = []
    const { code, data } = await store.dispatch('assetOverview/GetLamppostTotalClassify')
    if (code === 200) {
      data.forEach((item: any) => {
        xAxis.push(item.postTypeName)
        ydata.push(item.num)
      })
      state.lampPostList.xAxis = xAxis
      state.lampPostList.ydata = ydata
    }
  }
  // const getStreetList = async () => {
  //   state.streetList.push(['product', '配电设施', '灯杆', '灯具'])
  //   const { code, data } = await store.dispatch('assetOverview/GetStreetTotalList')
  //   if (code === 200) {
  //     data.forEach((item: any) => {
  //       state.streetList.push([item.name, item.relDistribution, item.relLampPost, item.relLampBase])
  //     })
  //   }
  // }

  // 工区设施投入对比图 数据源
  const getBarChartDataList = async (value?: string[]) => {
    let res
    value
      ? (res = await store.dispatch('assetOverview/GetAssetModelAreaDataReport', {
          deliverDateBegin: value[0],
          deliverDateEnd: value[1]
        }))
      : (res = await store.dispatch('assetOverview/GetAssetModelAreaDataReport'))

    if (res?.code === 200) {
      toTwoDimensionalMatrix('bar', res.data)
    }
    handleGetChartsStasticData() // 更新视图
  }

  // 月度设施投入走势图 数据源
  const getLineChartDataList = async (value?: string | string[]) => {
    let res
    value
      ? (res = await store.dispatch('assetOverview/GetAssetModelMonthInputDataReport', {
          deliverYear: value
        }))
      : (res = await store.dispatch('assetOverview/GetAssetModelMonthInputDataReport'))

    if (res?.code === 200) {
      toTwoDimensionalMatrix('line', res.data)
    }
    handleGetChartsStasticData() // 更新视图
  }

  // 数组对象转二维矩阵
  const toTwoDimensionalMatrix = (type: string, value: any) => {
    type === 'bar' ? (state.barChartDataList = []) : (state.lineChartDataList = []) // [[]]
    // 将接口返回的数据 重新组装成需要的数据格式 (数组对象转为二维矩阵式)
    const areaName = ['product'] // 小图标
    // 工区设施投入对比图 小图标
    if (type === 'bar') {
      value.map((item: { areaName: string }) =>
        areaName.indexOf(item.areaName) === -1 ? areaName.push(item.areaName) : ''
      )
      state.barChartDataList.push(areaName)
    }
    // 月度设施投入走势图 小图标
    if (type === 'line') {
      value.map((item: { modelName: string }) =>
        areaName.indexOf(item.modelName) === -1 ? areaName.push(item.modelName) : ''
      )
      state.lineChartDataList.push(areaName)
    }

    // 名称 (矩阵搭建完成)
    const modelName: any[] = [] // 第一项是字符, 后面是数字
    // 工区设施投入对比图
    if (type === 'bar') {
      value.map((item: { modelName: string }) =>
        modelName.indexOf(item.modelName) === -1 ? modelName.push(item.modelName) : ''
      )
    }
    // 月度设施投入走势图 x轴
    if (type === 'line') {
      value.map((item: { month: string }) =>
        modelName.indexOf(item.month) === -1 ? modelName.push(item.month) : ''
      )
    }

    // 对应行填到列对应数下 (矩阵填数)
    for (let k = 0; k < modelName.length; k++) {
      // 循环行
      const item = modelName[k]
      let modelNameAndNumber = [item]
      if (type === 'line') {
        modelNameAndNumber = [`${item}月`]
      }
      // 设左上角为(0, 0), 往右下角延伸, 第一行第一列开始填数
      // 列数组的第二项开始, 先从接口返回的数据源中拿到该行对应的值, 找到工区, 填进去
      for (let j = 1; j < areaName.length; j++) {
        const temp = areaName[j]
        for (let i = 0; i < value.length; i++) {
          const element = value[i]
          // 对应设备, 且是对应工区, 则存数字
          if (type === 'bar' && item === element.modelName && temp === element.areaName) {
            modelNameAndNumber.push(element.num)
            break
          }
          // 对应月份, 且是对应设备, 则存数字
          if (type === 'line' && item === element.month && temp === element.modelName) {
            modelNameAndNumber.push(element.num)
            break
          }
        }
      }
      // 一行设备填完就push进去
      type === 'bar'
        ? state.barChartDataList.push(modelNameAndNumber)
        : state.lineChartDataList.push(modelNameAndNumber)
    }
  }

  // 走势图的下拉框筛选 年数据
  const getYearData = () => {
    state.yearData = []
    for (let i = 2022; i <= day().year(); i++) {
      state.yearData.push(i)
    }
  }

  // 到日的可选日期限制
  const disabledDate = (time: Date) => {
    const oneYearAgo = parseInt(day().subtract(1, 'year').format('x'))
    return time.getTime() > Date.now() || time.getTime() < oneYearAgo
  }

  // 到年的可选日期限制
  const disabledYear = (time: Date) => {
    return time.getTime() > Date.now() || parseInt(day(time.getTime()).format('YYYY')) < 2000
  }

  // 日期选择器 筛选一段日期
  const handleDeliverDateChange = (value?: string[]) => {
    // 更新日期搜索

    window.localStorage.setItem(
      `assetOverviewCardsOrder${userInfo.content.userId}`,
      JSON.stringify(state.chartsStasticDataList)
    )
    // 更新视图
    for (let i = 0; i < state.chartsStasticDataList.length; i++) {
      const item = state.chartsStasticDataList[i]
      if (item.deliverDate === value) {
        if (item.type === 'zhanbitu') {
          getPieChartDataList(value)
        } else if (item.type === 'duibitu') {
          getBarChartDataList(value) // 工区设施投入对比图 饼图
        }
        break
      }
    }
  }

  // 走势图 搜索年份
  const selectYears = (value?: string | string[]) => {
    // 更新日期搜索
    window.localStorage.setItem(
      `assetOverviewCardsOrder${userInfo.content.userId}`,
      JSON.stringify(state.chartsStasticDataList)
    )
    getLineChartDataList(value)
  }

  // 图表统计 弹窗
  const handelChartsStasticOption = () => {
    state.showChartsStatisticOption = !state.showChartsStatisticOption
  }

  // 隐藏卡片
  const handelHiddenCards = (record: ChartsStasticDataListDataListItem) => {
    const info = JSON.parse(
      localStorage.getItem(`assetOverviewCardsInfo${userInfo.content.userId}`)!
    )
    const orderInfo = JSON.parse(
      localStorage.getItem(`assetOverviewCardsOrder${userInfo.content.userId}`)!
    ) // 上次缓存显示的数据
    // 更新所有数据
    for (let i = 0; i < info.length; i++) {
      const item = info[i]
      if (item.type === record.type) {
        item.show = !item.show
        break
      }
    }
    window.localStorage.setItem(
      `assetOverviewCardsInfo${userInfo.content.userId}`,
      JSON.stringify(info)
    ) // 卡片显隐 做本地浏览器缓存

    // 从上次显示顺序数据中 删这次点的隐藏 并存下来
    for (let i = 0; i < orderInfo.length; i++) {
      if (orderInfo[i].type === record.type) {
        orderInfo.splice(i, 1)
      }
    }

    window.localStorage.setItem(
      `assetOverviewCardsOrder${userInfo.content.userId}`,
      JSON.stringify(orderInfo)
    ) // 卡片显隐 做本地浏览器缓存
    handleGetChartsStasticData() // 更新视图
  }

  return () => {
    // 到日的日期选择 搜索
    const dateProps = {
      onChange: (value: any) => handleDeliverDateChange(value)
    }

    // 到年的日期选择 搜索
    const yearProps = {
      onChange: (value: any) => selectYears(value)
    }

    return (
      <>
        <ElRow gutter={EL_SPACE_SIZE_SECOND_GEAR}>
          {state.chartsStasticDataList &&
            state.chartsStasticDataList.map((item) => (
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElCard
                  shadow="never"
                  class={{
                    [styles['charts-stastic-item']]: true
                    // [styles['charts-stastic-item-margin']]: !(index % 2)
                  }}
                >
                  <div class={styles['statistic-title']}>
                    <SaasTitle type="primary">{item.name}</SaasTitle>
                    <div class={styles['data-pick-position']}>
                      {item.type === 'zoushitu' && (
                        <ElDatePicker
                          size="small"
                          placeholder="请选择年"
                          v-model={item.deliverDate}
                          type="year"
                          valueFormat="YYYY"
                          disabledDate={disabledYear}
                          clearable={false}
                          {...yearProps}
                        />
                      )}

                      {(item.type === 'duibitu' || item.type === 'zhanbitu') && (
                        <ElDatePicker
                          class={styles['data-pick-width']}
                          size="small"
                          v-model={item.deliverDate}
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          valueFormat="YYYY-MM-DD"
                          format="YYYY-MM-DD"
                          type="daterange"
                          disabledDate={disabledDate}
                          clearable
                          {...dateProps}
                        />
                      )}

                      {/* {item.type === 'zoushitu' ? (
                        <ElDatePicker
                          size="small"
                          placeholder="请选择年"
                          v-model={item.deliverDate}
                          type="year"
                          valueFormat="YYYY"
                          disabledDate={disabledYear}
                          clearable={false}
                          {...yearProps}
                        />
                      ) : (
                        <ElDatePicker
                          class={styles['data-pick-width']}
                          size="small"
                          v-model={item.deliverDate}
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          valueFormat="YYYY-MM-DD"
                          format="YYYY-MM-DD"
                          type="daterange"
                          disabledDate={disabledDate}
                          clearable
                          {...dateProps}
                        />
                      )} */}
                    </div>
                  </div>
                  {stateCharts.value &&
                    stateCharts.value.map((element) =>
                      item.type === element.type ? element.components : <>{''}</>
                    )}
                  {/* 隐藏 */}
                  <span
                    class={styles['charts-statistic-cards-show']}
                    onClick={() => handelHiddenCards(item)}
                  >
                    <ElIcon>
                      <Remove />
                    </ElIcon>
                  </span>
                </ElCard>
              </ElCol>
            ))}
          <ElCol {...SPAN_STYLE_DOUBLE}>
            {/* 加号卡片, 显隐 */}
            <ElCard shadow="hover" class={styles['charts-stastic-hidden']}>
              <div
                class={styles['charts-statistic-cards-add-icon']}
                onClick={handelChartsStasticOption}
              >
                {/* <AliIcon type="icon-xinzeng" /> */}
                {/* <AliIcon type="icon-tupianshangchuan" /> */}
                <ElImage src={plusImg} />
              </div>
            </ElCard>
          </ElCol>
        </ElRow>

        {/* 图表统计 弹窗 */}
        {state.showChartsStatisticOption && (
          <ChartsStatisticOption
            visible={state.showChartsStatisticOption}
            onCancel={handelChartsStasticOption}
            onHandleGetChartsStasticData={handleGetChartsStasticData}
          />
        )}
      </>
    )
  }
})
